const express = require('express');
const router = express.Router();
const tableSql = require('../db/tableSql');

// 获取球桌列表 / 按 room_id 查询
router.get('/api/tables', (req, res) => {
    const { room_id } = req.query;
    tableSql.getTableList(room_id, (err, tables) => {
        if (err) {
            return res.status(500).json({ code: 1, message: '查询失败', error: err });
        }
        res.json({ code: 0, data: tables });
    });
});

// 获取球桌详情
router.get('/api/tables/:table_id', (req, res) => {
    const { table_id } = req.params;
    tableSql.getTableById(table_id, (err, table) => {
        if (err) {
            return res.status(500).json({ code: 1, message: '查询失败', error: err });
        }
        if (!table) {
            return res.status(404).json({ code: 1, message: '未找到该球桌' });
        }
        res.json({ code: 0, data: table });
    });
});

// 新增球桌
router.post('/api/tables', (req, res) => {
    const { room_id, table_status } = req.body;
    if (!room_id || typeof table_status !== 'number') {
        return res.status(400).json({ code: 1, message: '参数错误' });
    }

    tableSql.createTable({ room_id, table_status }, (err, newTable) => {
        if (err) {
            return res.status(500).json({ code: 1, message: '新增失败', error: err });
        }
        res.status(201).json({ code: 0, data: newTable });
    });
});

// 更新球桌状态
router.put('/api/tables/:table_id/status', (req, res) => {
    const { table_id } = req.params;
    const { newStatus } = req.body;

    if (typeof newStatus !== 'number') {
        return res.status(400).json({ code: 1, message: '状态参数错误' });
    }

    tableSql.updateTableStatus(table_id, newStatus, (err, success) => {
        if (err) {
            return res.status(500).json({ code: 1, message: '更新失败', error: err });
        }
        if (!success) {
            return res.status(404).json({ code: 1, message: '未找到该球桌' });
        }
        res.json({ code: 0, message: '更新成功' });
    });
});

// 删除球桌
router.delete('/api/tables/:table_id', (req, res) => {
    const { table_id } = req.params;
    tableSql.deleteTable(table_id, (err, success) => {
        if (err) {
            return res.status(500).json({ code: 1, message: '删除失败', error: err });
        }
        if (!success) {
            return res.status(404).json({ code: 1, message: '未找到该球桌' });
        }
        res.json({ code: 0, message: '删除成功' });
    });
});

module.exports = router;
